#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月22日

@author: Administrator
'''
import logging
import datetime
from celery.task import task
from comment import settings
from comment.models import Comment
from common.decorators.celery import task_exception_handler
from django.db import connection, transaction
from elasticsearch.exceptions import TransportError
from common.utils import es

# 为loggers中定义的名称
logger = logging.getLogger("celery")

@task
@task_exception_handler
def update_comment_to_es_task(action):
    '''
    function: 
    '''
    try:
        es.es_client.index(settings.ES_INDEX_COMMENT_LIST, doc_type=settings.ES_INDEX_COMMENT_LIST_TYPE, body=action, id=action["id"])
        logger.info("update comment to es by id %s success;" % str(action["id"])) 
    except TransportError:
        logger.warning("update comment to es by id %s faild;" % str(action["id"]))
         
@task
@task_exception_handler
def comment_create_task(id):
    '''
    function: 评论创建后的异步处理函数， 此处对comment关联的Model进行comment_count和comment_time的属性变更
    
    id - Comment id
    '''
    
    try:
        related_fields = ('content_type',)
        only_fields = ('id', 'object_id', 'content_type', 'content_type__app_label', 'content_type__model')
        comment = Comment.objects.select_related(*related_fields).only(*only_fields).get(id=id)
    except Comment.DoesNotExist:
        return
    
    model_class = comment.content_type.model_class()
    object_id = comment.object_id
    
    if 'comment_count' in model_class._meta.get_all_field_names():
        cursor = connection.cursor()
        sql = 'UPDATE ' + model_class._meta.db_table + ' SET comment_count = (comment_count + 1) WHERE id=%(id)s'''
        cursor.execute(sql, {'id': object_id})
        transaction.commit_unless_managed()
        cursor.close()
    else:
        pass
    
    if 'comment_time' in model_class._meta.get_all_field_names():
        model_class.objects.filter(id=object_id).update(comment_time=datetime.datetime.now())
    else:
        pass
    

@task
@task_exception_handler
def comment_delete_task(id):
    '''
    function: 评论删除后的异步处理函数， 此处对comment关联的Model进行comment_count的属性变更
    
    id - Comment id
    '''
    
    try:
        related_fields = ('content_type',)
        only_fields = ('id', 'object_id', 'content_type', 'content_type__app_label', 'content_type__model')
        comment = Comment.objects.select_related(*related_fields).only(*only_fields).get(id=id)
    except Comment.DoesNotExist:
        return
    
    model_class = comment.content_type.model_class()
    object_id = comment.object_id
    
    if 'comment_count' in model_class._meta.get_all_field_names():
        cursor = connection.cursor()
        sql = 'UPDATE ' + model_class._meta.db_table + ' SET comment_count = (comment_count - 1) WHERE id=%(id)s'''
        cursor.execute(sql, {'id': object_id})
        transaction.commit_unless_managed()
        cursor.close()
    else:
        pass
